<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use DB;
class RegisterController extends Controller
{	
    //register
 
    public function register(Request $request)
    {	

    	if($request -> isMethod('POST'))
    		{
    			// $data = $request -> all();
	    		$this -> validate($request,[
	            'name' => 'min:6|max:18',
	            'password' => 'min:6|max:18',
	            'repassword' => 'same:password',
	            'email' => 'email',
	            'phone' => 'digits:11'
	            ],[
	            'name.min' => '用户名最少6位',
	            'name.max' => '用户名最多18位',
	            'password.min' => '密码最少6位',
	            'password.max' => '密码最多18位',
	            'repassword.same' => '确认密码不一致',
	            'email.email' => '请输入正确的邮箱格式',
	            'phone.digits' => '请输入11位数字是手机号'
	            ]);
	            $data = $request -> except('_token');
	            // dd($data);
	            $userData['name'] = $data['name'];
	            $userData['password'] = $data['password'];
	            $userData['email'] = $data['email'];
	            $userData['phone'] = $data['phone'];
	            $userData['airline'] = 0;
	            $userData['token'] = str_random(50);
	            $userData['password']   =  Crypt::encryptString($userData['password']);
	            $time = Date('Y-m-d H-i-s');
	            $userData['created_at'] = $time;
	            $userData['updated_at'] = $time;
	            $userInfo['created_at'] = $time;
	            $userInfo['updated_at'] = $time;
	            $userInfo['pic'] = '/uploads/avatar/default.jpg';
	            // DB::transaction(function ($userData) {
	            //     dd($userData);
	            //     $userInfo['user_id'] = DB::table('users')->insertGetId($userData);

	            //     DB::table('users_info')->insert($userInfo);
	            // });
	            DB::beginTransaction();
	            $userInfo['user_id'] = DB::table('users')->insertGetId($userData);
	            if($userInfo['user_id']  >0 )
	            {
	                $res  = DB::table('users_info')->insert($userInfo);
	                if($res)
		                {
		                   DB::commit();
		                   return redirect('home/user/login') -> with(['info' => '注册成功']);
		                }else{
		                   DB::rollback();
		                   // return back() -> with(['info' => '添加失败']);
		                }
	            }else
	            {
	                DB::rollback();
	                // return back() -> with(['info' => '添加失败']);
	            }
	    	}else
	    	{
	            return view('home.user.register', ['title' => '用户注册']);
			}
    }

}